package cn.com.w.bootfreemarker.util;



import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

public class DownDocUtil {

    Logger log = LoggerFactory.getLogger(DownDocUtil.class);


    /**
     *
     * @param fileId 文件id
     * @param request
     * @param response
     */
    public void downloadFile(String fileId, HttpServletRequest request, HttpServletResponse response) {
        String filePath = request.getSession().getServletContext().getRealPath("/")
                + "WEB-INF" + File.separator + "downloadword" + File.separator;

        String fileName = fileId + ".doc";
        String realPath = filePath +fileName;
        File file = new File(realPath);
        if (!file.exists()) {
            return;
        }
        OutputStream outputStream = null;
        InputStream inputStream = null;
        try {
            byte[] data = new byte[(int)file.length()];
            inputStream = new FileInputStream(file);
            //FileUtils.readFileToByteArray(file);
            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=\"" + java.net.URLEncoder.encode("xxx.doc", "UTF-8") + "\"");
            response.addHeader("Content-Length", "" + data.length);
            response.setContentType("application/octet-stream;charset=UTF-8");
            outputStream = new BufferedOutputStream(response.getOutputStream());
            int read = 0;
            while ((read = inputStream.read(data)) != -1) {
                outputStream.write(data, 0, read);
            }
            outputStream.flush();
        } catch (IOException e) {
            log.error("下载一个报告异常",e);
        } finally {
            try {
                inputStream.close();
            } catch (IOException e1) {
                log.error("关闭inputStream异常",e1);
            }
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                log.error("关闭outputStream异常",e);
            }
        }
    }
}
